package com.topcheer.provider.auth.service.impl;

import com.topcheer.common.base.CommonConstants;
import com.topcheer.common.base.exception.UserAuthException;
import com.topcheer.provider.auth.jwt.JwtTokenUtil;
import com.topcheer.provider.auth.jwt.vo.JwtAuthenticationRequest;
import com.topcheer.provider.auth.service.AuthService;
import com.topcheer.provider.rbac.entity.User;
import com.topcheer.provider.rbac.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author xutao
 * @Package com.topcheer.provider.auth.service.impl
 * @Description: ${todo}
 * @date 2020/4/8 9:27
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    UserService userService;

    @Autowired(required = false)
    JwtTokenUtil jwtTokenUtil;
    private BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(CommonConstants.PWD_SALT);

    @Override
    public String login(JwtAuthenticationRequest authenticationRequest) throws Exception {
        User user = new User();
        user.setLoginName(authenticationRequest.getUsername());
        List<User> userList = userService.select(user);
        if (!CollectionUtils.isEmpty(userList)) {
            User dbUser = userList.get(0);
            if (bCryptPasswordEncoder.matches(authenticationRequest.getPassword(), dbUser.getPassword())) {
                return jwtTokenUtil.generateToken(authenticationRequest.getUsername());
            }
        }
        throw new UserAuthException("username or password is invalid", HttpStatus.FORBIDDEN.value());
    }

    @Override
    public String refresh(String oldToken) throws Exception {
        return jwtTokenUtil.generateToken(jwtTokenUtil.getUsernameFromToken(oldToken));
    }

    @Override
    public void validate(String token) throws Exception {

    }
}
